import { Button, Form, message, Modal, Select } from "antd";
import React, { useEffect, useState } from "react";
import { getSameGradeClass } from "../../../api/student";

const { Option } = Select;

const ChooseModal = ({ visible, onCancel, onOk, editingStudent }) => {
    const [loading, setLoading] = useState(false);
    const [classList, setClassList] = useState([]);
    const [form] = Form.useForm();

    // 获取班级列表
    const fetchChooseList = async () => {
        if (!editingStudent?.specialtyId || !editingStudent?.grade) {
            message.error("缺少专业或年级信息，无法获取班级列表");
            return;
        }

        setLoading(true);
        try {
            const res = await getSameGradeClass({
                specialtyId: editingStudent.specialtyId,
                grade: editingStudent.grade,
            });
            setClassList(res.data || []);
        } catch (error) {
            message.error('获取班级列表失败');
            console.error("获取班级列表失败:", error);
        } finally {
            setLoading(false);
        }
    };

    // 初始化加载数据
    useEffect(() => {
        if (visible && editingStudent) {
            form.resetFields();
            fetchChooseList();
        }
    }, [visible, editingStudent, form]);

    // 提交表单
    const handleOk = async () => {
        try {
            const values = await form.validateFields();
            // 合并选中班级 ID 到 student 对象
            const updatedStudent = {
                ...editingStudent,
                classId: values.classId,
            };
            await onOk(updatedStudent);
        } catch (error) {
            console.error("提交失败：", error);
        } finally {
            setLoading(false);
        }
    };

    return (
        <Modal
            title="选择班级"
            open={visible}
            onOk={handleOk}
            onCancel={() => {
                form.resetFields();
                onCancel();
            }}
            confirmLoading={loading}
            footer={[
                <Button key="cancel" onClick={onCancel}>
                    取消
                </Button>,
                <Button key="submit" type="primary" loading={loading} onClick={handleOk}>
                    提交
                </Button>
            ]}
        >
            <Form form={form} layout="vertical" name="class_select_form">
                <Form.Item
                    label="班级"
                    name="classId"
                    rules={[{ required: true, message: '请选择班级！' }]}
                >
                    <Select placeholder="请选择班级">
                        {classList.map(cls => (
                            <Option key={cls.classId} value={cls.classId}>
                                {cls.className}
                            </Option>
                        ))}
                    </Select>
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default ChooseModal;